<?php

namespace App\Models;

use App\Helpers\Code;
use App\Models\Account\UserGroupMapUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Account\UserCache;

class BaseModel extends Model
{

    const limit = 15;

    public function getDataScope()
    {
        return Auth::user()->data_scope;
    }

    public function throwError($e)
    {
        Log::channel('errordaily')->error($e->getFile() . ' 第' . $e->getLine() . '行，错误信息：' . $e->getMessage());
        return Code::INSIDE_DATABASE_ERROR;
    }

    public function buildSql($routeName, $model)
    {
        //暂未开启此功能
        return $model;
        $userId = Auth::id();
        //判断用户是否为管理员
        $adminGroup = UserGroupMapUser::where('group_id', Code::SUPER_ADMIN_GROUP_ID)->where('user_id', $userId)->count();
        if ($adminGroup === 1) {
            return $model;
        }

        $cache = UserCache::where('user_id', $userId)->where('type', 1)->first(['cache']);

        $cacheScopes = json_decode($cache->cache, true);

        if (isset($cacheScopes['scopes'][$routeName])) {
            $scopes = $cacheScopes['scopes'][$routeName];

            $count = count($scopes[0]);

            if ($count === 1) {
                $where = $model->whereRaw("left(data_scope," . $scopes[1][0] . ") = '" . $scopes[0][0] . "'");
            } else {
                $where = $model->whereRaw("left(data_scope," . $scopes[1][0] . ") = '" . $scopes[0][0] . "'");

                for ($i = 1; $i < $count; $i++) {
                    $where->orWhereRaw("left(data_scope," . $scopes[1][$i] . ") = '" . $scopes[0][$i] . "'");
                }
            }

            return $where;
        }

        return $model;
    }

}
